import { _decorator, Component, Node, CCFloat } from 'cc';
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = MovingSceneBg
 * DateTime = Fri Jan 07 2022 15:32:53 GMT+0800 (中国标准时间)
 * Author = Kesa
 * FileBasename = MovingSceneBg.ts
 * FileBasenameNoExtension = MovingSceneBg
 * URL = db://assets/Scripts/MovingSceneBg.ts
 * ManualUrl = https://docs.cocos.com/creator/3.3/manual/zh/
 *
 */

@ccclass('MovingSceneBg')
export class MovingSceneBg extends Component {
    @property(Node)
    bg01: Node = null;

    @property(Node)
    bg02: Node = null;

    @property(CCFloat)
    bgSpeed = 10;

    // 背景图片间隔
    @property(CCFloat)
    bgGapOffset = 160;

    // 背景高度
    @property(CCFloat)
    bgHeight = -120;

    start() {
        this._init();
    }

    update(deltaTime: number) {
        // [4]
        this._moveBackground(deltaTime);
    }

    // 开始重置坐标
    private _init() {
        this.bg01.setPosition(0, this.bgHeight, 0);
        this.bg02.setPosition(0, this.bgHeight, -this.bgGapOffset);
    }

    // 移动方法
    private _moveBackground(deltaTime: number) {
        // 正常移动
        this.bg01.setPosition(0, this.bgHeight, this.bg01.position.z + this.bgSpeed * deltaTime);
        this.bg02.setPosition(0, this.bgHeight, this.bg02.position.z + this.bgSpeed * deltaTime);

        // 超出边界重置位置到另一个背景后面
        if (this.bg01.position.z > this.bgGapOffset) {
            this.bg01.setPosition(0, this.bgHeight, this.bg02.position.z - this.bgGapOffset);
        }
        if (this.bg02.position.z > this.bgGapOffset) {
            this.bg02.setPosition(0, this.bgHeight, this.bg01.position.z - this.bgGapOffset);
        }
    }
}
